import pygame
import random

# 初始化 Pygame
pygame.init()

# 设置屏幕大小
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))

# 设置标题
pygame.display.set_caption("Catch the Ball Game")

# 设置颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)

# 设置玩家平台属性
player_width = 100
player_height = 20
player_x = (screen_width - player_width) // 2
player_y = screen_height - player_height - 10
player_speed = 10

# 设置球属性
ball_radius = 15
balls = []
num_balls = 3  # 设置同时在屏幕上的球的数量
ball_speed_min = 2
ball_speed_max = 5

# 设置分数
score = 0

# 设置游戏循环的标志
running = True

# 设置游戏循环的帧率
clock = pygame.time.Clock()

# 定义绘制文本的函数
def draw_text(surface, text, size, x, y):
    font_name = pygame.font.match_font('arial')
    font = pygame.font.Font(font_name, size)
    text_surface = font.render(text, True, WHITE)
    text_rect = text_surface.get_rect()
    text_rect.midtop = (x, y)
    surface.blit(text_surface, text_rect)

# 游戏主循环
while running:
    # 填充背景色
    screen.fill(BLACK)

    # 事件监听
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 玩家控制
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and player_x > 0:
        player_x -= player_speed
    if keys[pygame.K_RIGHT] and player_x < screen_width - player_width:
        player_x += player_speed

    # 球的控制
    for i in range(num_balls):
        if len(balls) < num_balls:
            # 创建新球
            balls.append({
                'x': random.randint(ball_radius, screen_width - ball_radius),
                'y': 0,
                'visible': True,
                'speed': random.randint(ball_speed_min, ball_speed_max),
                'color': (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
            })

        elif len(balls) > 0:
            ball = balls[i]
            if ball['visible']:
                ball['y'] += ball['speed']
                if ball['y'] > screen_height:
                    ball['visible'] = False
                    score -= 1  # 球落地，扣一分

                # 检测球和平台的碰撞
                if player_y < ball['y'] + ball_radius < player_y + player_height and \
                   player_x < ball['x'] + ball_radius < player_x + player_width:
                    ball['visible'] = False
                    score += 1  # 接到球，加一分

                # 绘制球
                pygame.draw.circle(screen, ball['color'], (int(ball['x']), int(ball['y'])), ball_radius)

    # 移除已经落地的球
    balls = [ball for ball in balls if ball['visible']]

    # 绘制玩家平台
    pygame.draw.rect(screen, GREEN, (player_x, player_y, player_width, player_height))

    # 绘制分数
    draw_text(screen, f"Score: {score}", 18, screen_width / 2, 10)

    # 更新屏幕
    pygame.display.flip()

    # 控制游戏帧率
    clock.tick(60)

# 退出 Pygame
pygame.quit()